package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentAudit;
import com.mxpio.erp.common.equipment.entity.EquipmentAuditOperation;
import com.mxpio.erp.common.equipment.entity.EquipmentAuditTransfer;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpBasics;
import com.mxpio.erp.common.equipment.service.EquipmentAreaService;
import com.mxpio.erp.common.equipment.service.EquipmentAuditService;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.entity.User;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 稽核管理Service业务层处理
 *
 * @author Cheng
 * @date 2023-07-10
 */
@Service
public class EquipmentAuditServiceImpl extends BaseServiceImpl<EquipmentAudit> implements EquipmentAuditService {

    @Resource
    private EquipmentAreaService equipmentAreaService;

    @Override
    @Transactional
    public void saveAudit(EquipmentAudit equipmentAudit) {
        //设置删除状态为正常
        equipmentAudit.setIsDel(0);
        //设置工单编码
        //equipmentAudit.setOrderCode(OrderNumberUtil.getCode("JH"));
        //设置稽核时间
        equipmentAudit.setAuditTime(new Date());
        if ("NG".equals(equipmentAudit.getAuditState())) {
            //设置状态
            equipmentAudit.setOrderStatus(EquipmentEnums.AuditStatus.APPLY.getCode());
        } else {
            //设置状态
            equipmentAudit.setOrderStatus(EquipmentEnums.AuditStatus.CHECKED.getCode());
        }
        //未选择申请用户时设置为当前用户
        if (StringUtils.isEmpty(equipmentAudit.getAuditorId())) {
            equipmentAudit.setAuditorId(SecurityUtils.getLoginUsername());
        }
        //区域时设置区域名称，编码
        String targetType = equipmentAudit.getTargetType();
        String targetId = equipmentAudit.getTargetId();
        if(!StringUtils.isEmpty(targetId)){
            /*if ("area".equals(targetType)) {
                EquipmentArea equipmentArea = JpaUtil.getOne(EquipmentArea.class, targetId);
                String name = equipmentAreaService.getParentAllNameByPid(equipmentArea.getPid());
                equipmentAudit.setTargetName(name + " " + equipmentArea.getAreaName());
                equipmentAudit.setTargetCode(equipmentArea.getAreaCode());
            }else*/ if("eqp".equals(targetType)) {
                EquipmentEqpBasics basics = JpaUtil.getOne(EquipmentEqpBasics.class, targetId);
                equipmentAudit.setTargetName(basics.getEqpName());
                equipmentAudit.setTargetCode(basics.getEqpCode());
            }
        }

        //保存
        this.save(equipmentAudit);
        //添加操作历史
        insertOperate(equipmentAudit.getId(), "稽核申请", "稽核申请");

    }

    /**
     * 添加操作记录
     *
     * @param repairId 维修ID
     * @param operate  操作
     * @param reason   原因（主要用具回退填写原因）
     */
    private void insertOperate(String repairId, String operate, String reason) {
        EquipmentAuditOperation operation = new EquipmentAuditOperation();
        //设置维修ID
        operation.setAuditId(repairId);
        //设置操作名称
        operation.setOperate(operate);
        //设置操作原因
        operation.setReason(reason);
        //设置操作时间
        operation.setOperateTime(new Date());
        //获取当前登录用户
        User loginUser = SecurityUtils.getLoginUser();
        //设置操作人
        operation.setOperator(loginUser.getNickname() + "/" + loginUser.getUsername());
        //保存
        JpaUtil.save(operation);
    }

    /**
     * 添加操作记录
     *
     * @param repairId 维修ID
     * @param operate  操作
     * @param reason   原因（主要用具回退填写原因）
     * @param time     时间戳
     */
    private void insertOperate(String repairId, String operate, String reason, long time) {
        EquipmentAuditOperation operation = new EquipmentAuditOperation();
        //设置维修ID
        operation.setAuditId(repairId);
        //设置操作名称
        operation.setOperate(operate);
        //设置操作原因
        operation.setReason(reason);
        //设置操作时间
        operation.setOperateTime(new Date(time));
        //获取当前登录用户
        User loginUser = SecurityUtils.getLoginUser();
        //设置操作人
        operation.setOperator(loginUser.getNickname() + "/" + loginUser.getUsername());
        //保存
        JpaUtil.save(operation);
    }

    @Override
    @Transactional
    public void send(EquipmentAudit equipmentAudit) {
        EquipmentAudit bean = this.getById(EquipmentAudit.class, equipmentAudit.getId());

        if (StringUtils.isEmpty(equipmentAudit.getId()) || bean == null) {
            throw new MBootException("id为空或者未找到对应实体！");
        }
        //派工人员信息
        bean.setRectId(equipmentAudit.getRectId());
        bean.setSendTime(new Date());
        //改变状态---设置为派工状态
        bean.setOrderStatus(EquipmentEnums.AuditStatus.SEND.getCode());
        this.update(bean);
        //添加操作记录
        insertOperate(equipmentAudit.getId(), "稽核派工", "稽核派工");
    }

    @Override
    @Transactional
    public void reSendAuditById(String reason, String username, String id) {
        EquipmentAudit tpmRepair = this.getById(EquipmentAudit.class, id);
        if (StringUtils.isEmpty(id) || tpmRepair == null) {
            throw new MBootException("id为空或者未找到对应实体！");
        }
        //设置改派记录
        EquipmentAuditTransfer transfer = new EquipmentAuditTransfer();
        transfer.setAuditId(id);
        User loginUser = SecurityUtils.getLoginUser();
        transfer.setNewExecutor(loginUser.getNickname() + "/" + loginUser.getUsername());
        //设置旧的人员信息
        User  oldUser = JpaUtil.linq(User.class).equal("username",tpmRepair.getRectId()).findOne();
        transfer.setOldExecutor(oldUser.getNickname() + "/" + oldUser.getUsername());
        transfer.setReason(reason);
        transfer.setType("维修执行");
        JpaUtil.save(transfer);

        //设置新的改派人
        tpmRepair.setRectId(username);
        this.update(tpmRepair);
        //设置操作记录
        insertOperate(id, "维修改派", reason);
    }

    @Override
    @Transactional
    public void finish(EquipmentAudit equipmentAudit) {
        EquipmentAudit bean = this.getById(EquipmentAudit.class, equipmentAudit.getId());
        if (bean == null
                || !EquipmentEnums.AuditStatus.SEND.getCode().equals(bean.getOrderStatus())) {
            throw new MBootException("实体未找到或未派工状态！");
        }
        //设置工单状态
        bean.setOrderStatus(EquipmentEnums.AuditStatus.AUDIT.getCode());
        //设置整改完成时间
        bean.setRectFinishTime(equipmentAudit.getRectFinishTime());
        //设置整改描述
        bean.setRectDesc(equipmentAudit.getRectDesc());
        //设置整改图片
        bean.setRectPic(equipmentAudit.getRectPic());
        bean.setOverFlag(0);
        //设置是逾期原因
        if (equipmentAudit.getOverFlag() == 1) {
            bean.setOverFlag(1);
            bean.setOverReason(equipmentAudit.getOverReason());
        }
        this.update(bean);

        //设置操作记录
        insertOperate(bean.getId(), "稽核整改完成", "稽核整改完成");
    }

    @Override
    @Transactional
    public void check(String id, HttpServletRequest request) {
        EquipmentAudit equipmentAudit = this.getById(EquipmentAudit.class, id);
        if (equipmentAudit == null || !EquipmentEnums.AuditStatus.AUDIT.getCode().equals(equipmentAudit.getOrderStatus())) {
            throw new MBootException("实体未找到或非整改完成状态！");
        }
        equipmentAudit.setOrderStatus(EquipmentEnums.AuditStatus.CHECKED.getCode());
        equipmentAudit.setAccpTime(new Date());
        //获取当前登录用户
        equipmentAudit.setAccpId(SecurityUtils.getLoginUsername());
        this.update(equipmentAudit);
        //设置操作记录
        insertOperate(id, "稽核验收", "稽核验收");
    }

    @Override
    @Transactional
    public void reject(String id, String reason) {
        EquipmentAudit equipmentAudit = this.getById(EquipmentAudit.class, id);
        if (equipmentAudit == null || !EquipmentEnums.AuditStatus.AUDIT.getCode().equals(equipmentAudit.getOrderStatus())) {
            throw new MBootException("实体未找到或非整改完成状态！");
        }

        equipmentAudit.setOrderStatus(EquipmentEnums.AuditStatus.SEND.getCode());
        this.update(equipmentAudit);

        //设置操作记录
        insertOperate(id, "验收回退", reason);
    }

    @Override
    @Transactional
    public void signOffBack(String id, String reason) {
        EquipmentAudit equipmentAudit = this.getById(EquipmentAudit.class, id);
        if (equipmentAudit == null || !EquipmentEnums.AuditStatus.CHECKED.getCode().equals(equipmentAudit.getOrderStatus())) {
            throw new MBootException("实体未找到或非整改完成状态！");
        }

        equipmentAudit.setOrderStatus(EquipmentEnums.AuditStatus.SEND.getCode());
        this.update(equipmentAudit);

        //设置操作记录
        insertOperate(id, "签核回退", reason);
    }

    @Override
    @Transactional
    public void executeOffLineData(EquipmentAudit equipmentAudit) {
        EquipmentAudit bean = this.getById(EquipmentAudit.class, equipmentAudit.getId());
        if (bean == null) {
            throw new MBootException("根据id:" + equipmentAudit.getId() + "查询实体不存在！");
        }
        this.update(equipmentAudit);
        //保存维修记录
        insertOperate(equipmentAudit.getId(), "稽核整改完成", "稽核整改完成", equipmentAudit.getRectFinishTime().getTime());
    }
}
